/**
 * 工具类方法
 */
import Moment from 'dayjs'

export default {
	initFresh() {
		uni.startPullDownRefresh()
	},

	previewImg(urls, showMenu = false) {
		uni.previewImage({
			showmenu: showMenu,
			urls: urls
		})
	},

	getDayTimeFirst(date) {
		let d = typeof date === 'number' ? new Date(date) : date
		return new Date(d.toLocaleDateString()).getTime()
	},

	//获取指定日期最后1ms时间戳
	getDayTimeLast(date) {
		const d = new Date(date)
		d.setHours(23, 59, 59, 999)
		return d.getTime()
	},

	getFirstDayOfMonth(year, month) {
		return Moment([year, month - 1, 1]).valueOf();
	},

	getLastDayOfMonth(year, month) {
		return Moment([year, month - 1]).endOf('month').valueOf();
	},

	getMondayDate(date) {
		return Moment(date).startOf('isoWeek').valueOf();
	},

	getSundayDate(date) {
		return Moment(date).endOf('isoWeek').valueOf();
	},

	judegIsCurToday(time) {
		let date = new Date()
		let todayTime = this.getDayTimeFirst(date)
		let curTime = this.getDayTimeFirst(time)
		let range = curTime < todayTime ? -1 : curTime > todayTime ? 1 : 0
		return range
	},

	getStatusBarHeight() {
		let systemInfo = uni.getWindowInfo()
		return systemInfo.statusBarHeight
	},

	// 获取系统信息
	getSystemInfo() {
		return new Promise((resolve, reject) => {
			uni.getSystemInfo({
				success: res => resolve(res),
				fail: err => reject(err)
			})
		})
	},

	// Toast
	showToast(title, position = 'center', icon = 'none') {
		uni.showToast({
			icon,
			title,
			position
		})
	},

	// 打电话
	makeCall(phoneNum) {
		uni.makePhoneCall({
			phoneNumber: phoneNum
		})
	},

	/**
	 * 手机号脱敏
	 */
	desensitizePhone(phone) {
		const phoneStr = String(phone).trim();
		// 正则匹配11位有效手机号（以1开头，第二位3-9）
		if (/^1[3-9]\d{9}$/.test(phoneStr)) {
			// 使用正则替换中间4位为****
			return phoneStr.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
		return phoneStr; // 无效手机号返回原值
	},

	/**
	 * 日期格式化
	 */
	dateFormat(date, format = 'YYYY-MM-DD HH:mm:ss') {
		if (!date) return ''
		return Moment(date).format(format)
	},

	// 获取当前时间
	getCurDate() {
		const nowDate = new Date().getTime()
		return this.dateFormat(nowDate, 'YYYY-MM-DD')
	},

	// 获取当前定位
	getLocation() {
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'gcj02', // wgs84 gcj02
				success: function(res) {
					resolve(res)
				},
				fail: function(err) {
					resolve(err)
				}
			})
		})
	},

	// 取视频文件第一帧作为封面图
	getCoverFromVideo(videoUrl) {
		return `${videoUrl}?x-oss-process=video/snapshot,t_0,f_jpg`
	},

	// 页面跳转【保留当前页面】
	navigateToPage(url, params = null, animationType = 'slide-in-right') {
		let pageUrl = params ? `${url}?${params}` : url
		uni.navigateTo({
			url: pageUrl,
			animationType
		})
	},

	// 页面返回【保留当前页面】
	navigateBackToPage(url, params = null, animationType = 'slide-out-right') {
		if (url) {
			let pageUrl = params ? `${url}?${params}` : url
			uni.navigateBack({
				url: pageUrl,
				animationType
			})
		} else {
			uni.navigateBack({
				delta: 1,
				animationType
			})
		}
	},

	// 页面跳转【不保留当前页面】
	redirectToPage(url, params = null) {
		let pageUrl = params ? `${url}?${params}` : url
		uni.redirectTo({
			url: pageUrl
		})
	},

	// 页面跳转【关闭所有页面，打开应用内的某个页面】
	reLaunchToPage(url, params = null) {
		let pageUrl = params ? `${url}?${params}` : url
		uni.reLaunch({
			url: pageUrl
		})
	},

	// 跳转到tabbar页面
	switchTabToPage(pagePath) {
		uni.switchTab({
			url: pagePath
		})
	},

	// 回到顶部
	scrollToTop() {
		uni.pageScrollTo({
			scrollTop: 0
		})
	},

	// 校验日期区间
	verifyDateBetween(startDate, endDate) {
		let newSDate = +(startDate.replace(/-/g, ''))
		let newEDate = +(endDate.replace(/-/g, ''))
		return newSDate - newEDate > 0
	},

	// 获取本地应用资源版本号
	getAppCurVersionInfo() {
		return new Promise((resolve, reject) => {
			plus.runtime.getProperty(
				plus.runtime.appid,
				function(inf) {
					resolve(inf)
				}
			)
		})
	},

	// 动态设置列表页是否支持刷新
	setRefresh(isSupport = false) {
		const pages = getCurrentPages()
		const page = pages[pages.length - 1]
		const currentWebview = page.$getAppWebview()
		currentWebview.setStyle({
			pullToRefresh: {
				support: isSupport
			}
		})
	},

	// 从身份证号中获取性别
	getInfoFromIdCard(val) {
		let iden = val
		let sex = null
		let age = 0
		let myDate = new Date()
		let month = myDate.getMonth() + 1
		let day = myDate.getDate()
		let birthday = ''

		if (iden.length === 18) {
			age = myDate.getFullYear() - iden.substring(6, 10) - 1
			sex = iden.substring(16, 17)
			if (
				iden.substring(10, 12) < month ||
				(iden.substring(10, 12) === month && iden.substring(12, 14) <= day)
			) {
				age++
			}

			// 获取出生年月日
			let bir_year = iden.substring(6, 10)
			let bir_month = iden.substring(10, 12)
			let bir_day = iden.substring(12, 14)
			birthday = `${bir_year}-${bir_month}-${bir_day}`
		}
		if (iden.length === 15) {
			age = myDate.getFullYear() - iden.substring(6, 8) - 1901
			sex = iden.substring(13, 14)
			if (
				iden.substring(8, 10) < month ||
				(iden.substring(8, 10) === month && iden.substring(10, 12) <= day)
			) {
				age++
			}
		}
		sex = sex % 2 === 0 ? 'FEMALE' : 'MALE'
		return {
			age,
			gender: {
				name: sex === 'FEMALE' ? '女' : '男',
				value: sex
			},
			birthday
		}
	},

	// 从集合中查找相应字段
	findFieldFromList(value, targetField, returnField, list) {
		if (list.length === 0) return
		let result = list.find(item => item[targetField] === value)
		if (result) {
			return result[returnField]
		} else {
			return ''
		}
	},

	// 分钟转时间（一日中的）
	convertMinutesToDayTime(minutes) {
		if (!isNaN(minutes)) {
			const m = minutes % 60
			const h = (minutes - m) / 60
			let s = h < 10 ? '0' + h : '' + h
			s += ':'
			s += m < 10 ? '0' + m : '' + m
			return s
		}
		return minutes
	},

	//是否为空
	fieldIsEmpty(val) {
		let type = typeof val
		switch (type) {
			case 'undefined':
				return true
			case 'object':
				if (Array.isArray(val)) {
					let flag = true;
					if (val.length > 0) {
						for (let v of val) {
							if (typeof v !== 'undefined') {
								flag = false
								return
							}
						}
					}
					return flag
				} else {
					return Object.keys(val).length < 1
				}
			case 'boolean':
				return val
			case 'number':
				return val === 0
			case 'string':
				return val.trim() === ''
		}
	},

	convertToStar(value) {
		let starList = ['*', '*', '*', '*']
		if (value === 0) return starList.join(' ')
		let len = String(value).length
		starList = []
		for (let i = 0; i < len; i++) {
			starList.push('*')
		}
		return starList.join(' ')
	},

	// 通过生日计算年龄
	getAge(birthday) {
		if (birthday) {
			const duration = Moment.duration(Moment().diff(Moment(birthday)))
			const years = duration.years()
			const months = duration.months()
			const days = duration.days()
			if (years > 0) {
				return years + '岁'
			} else {
				if (months > 0) {
					return months + '月'
				} else {
					return days + '天'
				}
			}
		}
		return ''
	},

	//获取指定日期零点时间戳
	getDayTimeFirst(date) {
		let d
		if (typeof date === 'object') {
			d = date
		} else {
			d = new Date(date)
		}
		return new Date(d.toLocaleDateString()).getTime()
	},

	//获取当前页面url参数
	getPageRouteParams() {
		let pages = getCurrentPages();
		let len = pages.length
		let currentPage = pages[len - 1]
		let options = currentPage.options
		return options
	},
  
  isOverFiveLines(element) {
    // 创建范围并选择元素内容
    const range = document.createRange();
    range.selectNodeContents(element);
    // 获取所有行的矩形信息
    const rects = range.getClientRects();
    console.log('文本行数：'+rects.length);
    // 判断行数是否超过5行
    return rects.length > 5;
  }
}